package com.lsh.oms.worker.service.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dangdang.ddframe.job.api.JobExecutionMultipleShardingContext;
import com.dangdang.ddframe.job.plugin.job.type.simple.AbstractSimpleElasticJob;
import com.lsh.oms.core.enums.OrderStatus;
import com.lsh.oms.core.model.order.OrderDetail;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.model.order.OrderShippingHead;
import com.lsh.oms.core.redis.RedisTemplate;
import com.lsh.oms.core.service.order.OrderQueryService;
import com.lsh.oms.core.service.other.ShippingOrderService;
import com.lsh.oms.core.utils.http.HttpClientTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Project Name: lsh-oms
 *
 * @author peter
 * @date 18/2/27
 * 北京链商电子商务有限公司
 * Package:
 * desc:
 */
@Slf4j
@Component
@Deprecated
public class BillNotifyWmJop extends AbstractSimpleElasticJob {


    @Autowired
    private OrderQueryService orderQueryService;

    @Autowired
    private ShippingOrderService shippingOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${wmUrl}")
    private String wmUrl;


    @Override
    public void process(JobExecutionMultipleShardingContext jobExecutionMultipleShardingContext) {

        try {

            Integer startTime = this.getStartTime();
            log.info("【推送物美订单发货数量】统计范围 {}", startTime);

            List<OrderHead> orderHeads = orderQueryService.findListByStatusRangeAndTimeRange(OrderStatus.ORDER_DELIVERY.getIndex(), OrderStatus.ORDER_SIGN.getIndex(), startTime);

            if (CollectionUtils.isEmpty(orderHeads)) {
                return;
            }

            log.info("【推送物美订单发货数量】订单数量 {}", orderHeads.size());
            for (OrderHead orderHead : orderHeads) {

                if (!StringUtils.isEmpty(redisTemplate.get("oms:wm:push:" + orderHead.getOrderCode()))) {
                    continue;
                }
                JSONObject req = new JSONObject();
                JSONObject orderext = JSON.parseObject(orderHead.getAddressInfo());
                String duoDianOrder = orderext.getString("DuoDianOrder");
                if(!StringUtils.isEmpty(duoDianOrder) && duoDianOrder.equals("1")){
                    redisTemplate.set("oms:wm:push:" + orderHead.getOrderCode(), "push");
                    continue;
                }

                Map<String, Object> ext = orderHead.extendedProperties();
                req.put("retailerNo", "wumart");
                req.put("obdNo", ext.get("remark"));

                Map<Integer, String> code2itemNo = new HashMap<>();
                if (orderHead.getOrderStatus() > OrderStatus.ORDER_DELIVERY.getIndex()) {
                    List<OrderDetail> detailList = orderQueryService.findDetails(orderHead.getOrderCode());

                    for (OrderDetail detail : detailList) {

                        JSONObject extAttr = JSON.parseObject(detail.getGoodsExtAttrs());
                        String obdNo = extAttr.getString("remark");

                        code2itemNo.put(detail.getItemCode(), obdNo);
                    }
                }

                if(CollectionUtils.isEmpty(code2itemNo)){
                    continue;
                }

                OrderShippingHead shippingHead = shippingOrderService.selectOneByOrderCode(orderHead.getOrderCode(), true);
                if (null == shippingHead) {
                    log.info(orderHead.getOrderCode() + " 发货数据存在 不能通知物美发货过账");
                    continue;
                }
                JSONArray items = new JSONArray();
                shippingHead.getDetails().forEach(detail -> {
                    JSONObject item = new JSONObject();

                    String obdNo = code2itemNo.get(detail.getItemCode());

                    item.put("obdItem", obdNo);
                    item.put("qty", detail.getRealQty().setScale(2));

                    items.add(item);
                });

                req.put("items", items);

                if (pushWm(req)) {
                    redisTemplate.set("oms:wm:push:" + orderHead.getOrderCode(), "push");
                }
            }
        } catch (Exception ex) {

            log.error("[通知物美发货过账] 异常", ex);
        }

    }

    private boolean pushWm(JSONObject req) {
        Map<String, String> head = new HashMap<>(8);
//        head.put("secretKey", secretKey);
        head.put("Content-Type", "application/json");

        log.info("oms wm push param is " + req.toJSONString());
        String res = HttpClientTemplate.doPostBody(wmUrl, req.toJSONString(), head);

        if (StringUtils.isEmpty(res)) {
            return false;
        }

        JSONObject dmall = JSON.parseObject(res);
        String code = dmall.getString("code");
        if (StringUtils.isEmpty(code) || !code.endsWith("0000")) {
            return false;
        }

        return true;
    }


    /**
     * 统计开始时间
     *
     * @return 时间戳
     */
    private Integer getStartTime() {

        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
//        cal.add(Calendar.DATE, -1);

        return (int) TimeUnit.MILLISECONDS.toSeconds(cal.getTime().getTime());
    }

}
